package com.kafka.study.util;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class TimeUtils {
    /**
     * 时间戳转时间字符串
     *
     * @param timestamp 时间戳
     * @return 本地时间
     */
    public static String timestampToDate(long timestamp) {
        // 将毫秒时间戳转换为 Instant 对象
        Instant instant= Instant.ofEpochMilli(timestamp);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 将 Instant 对象转换为 LocalDateTime 对象，使用系统默认时区
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).format(formatter);
    }

    /**
     * 时间字符串转时间戳
     *
     * @param time 时间字符串
     * @return 时间戳
     */
    public static long stringToTimestamp(String time) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse(time, formatter);
        Instant instant = localDateTime.toInstant(ZoneOffset.of("+8"));
        return instant.toEpochMilli();
    }
}
